import {
  createRouter,
  createWebHashHistory
} from "vue-router";

import NProgress from './nprogress'

import { i18n } from "@/config";
// "getActivePinia()" was called but there was no active Pinia. Are you trying to use a store before calling "app.use(pinia)"?
import { pinia } from '@/stores'
// 引入 usePermissionStore - 路由
import { usePermissionStore } from '@/stores/modules/permission'
import { storeToRefs } from "pinia";
// const Markdown = () => import('@/components/markdown.vue')

/** 路由白名单 */
const whiteList = ["/login", "/world"];

export const routes = [
  {
    path: "/",
    name: "Login",
    alias: '/login',
    hidden: true,
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: 'menus.loginTitle'
    }
  },
  {
    path: "/world",
    name: "World",
    hidden: true,
    component: () => import("@/views/world/index.vue"),
    meta: {
      title: 'buttons.world'
    }
  },
  // 页面刷新警告 No match found for location with path
  {
    path: "/:pathMatch(.*)*", // 必备
    hidden: true,
    meta: {
      title: 'not found route'
    },
    component: () => import("@/views/error/404.vue"), 
  },
  /* {
    path: "/doc/:name",
    hidden: true,
    name: "Markdown",
    title: "Markdown",
    component: Markdown,
    meta: {
      title: 'Markdown'
    }
  }, */
  {
    path: "/404",
    name: "404",
    hidden: true,
    component: () => import("@/views/error/404.vue"),
    meta: {
      title: '404'
    }
  }
]

export function getRoutes() {
  const modules = import.meta.glob('./modules/*.ts', { eager: true })
  const entries = Object.entries(modules).map(([key, value]: any) => {
    return value.default
  })
  return entries
}
export const asyncRoutes = getRoutes()

const router = createRouter({
  // createWebHashHistory() --- Hash 模式
  // createWebHistory() --- HTML5 模式
  // createMemoryHistory() --- Memory 模式
  history: createWebHashHistory(),
  routes: routes
})

function getI18nLanguage(message: any) {
  /* 
    i18n.global.t 的方法：
    function t(...args) {
      return wrapWithDeps((context) => Reflect.apply(translate, null, [context, ...args]), () => parseTranslateArgs(...args), "translate", (root) => Reflect.apply(root.t, root, [...args]), (key) => key, (val) => isString(val));
    }
  */
  // return i18n.global.t.call(i18n.global.locale, message, ...arguments)
  /* 
    i18n.global.t.call(i18n.global.locale, message)
    ComposerTranslation<{}, string, RemoveIndexSignature<{
      [x: string]: LocaleMessageValue<VueMessageType>;
    }>, never, never, never> | VueI18nTranslation<...>
  */
  return i18n.global.t.apply(i18n.global.locale, Array.of(message))
}
const permissionStore = usePermissionStore(pinia)
const { isLogin, hasRoutes } = storeToRefs(permissionStore)

router.beforeEach((to: any, _from:any, next: any) => {
  NProgress.start();
  const isI18n = to.meta.title && to.meta.title.includes('.')
  document.title = (isI18n ? getI18nLanguage(to.meta.title) : to.meta.title) + ' | algate-admin'
  if(isLogin) {
    if(!hasRoutes.value) {
      /* asyncRoutes.forEach(route => {
        router.options.routes.push(route)
        router.addRoute(route)
      })
      hasRoutes.value = true */
      permissionStore.setLogin()
      next({ ...to, replace: true })
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      console.log(2)
      next();
    } else {
      console.log(3)
      next({ path: '/login' });
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});

export { router }

// 此处的hook为了测试 setup 中使用 t 的问题而写；现在只作为hook范例
/* export function useRouteHook() {
  const router = createRouter({
    history: createWebHashHistory(),
    routes
  })

  // t 只能在setup函数中使用
  // const { t } = useI18n()
  function getI18nLanguage(message: any) {
    return t(message)
  }

  router.beforeEach((to: any, _from:any, next: any) => {
    NProgress.start();
    const isI18n =  to.meta.title.includes('.')
    document.title = (isI18n ? getI18nLanguage(to.meta.title) : to.meta.title) + ' | algate-admin'
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next();
    }
  });

  router.afterEach(() => {
    NProgress.done();
  });

  return {
    router
  }
}
 */